import {
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Select,
  SelectOption,
  Space,
  TypographyText
} from 'ant-design-vue'
import { fa } from 'element-plus/lib/locale'
import { cloneDeep } from 'lodash-es'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { omit } from 'xe-utils'

import { marketingApi } from '@/apis'
import { ExpressTempleteItem } from '@/apis/jindouGiftTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { provinceList } from '@/utils'

export default defineComponent({
  name: 'YxExpressTemplete',
  setup() {
    const showDialog = ref(false)
    const dialogLoading = ref(false)
    const pList = ref(provinceList)
    const optionItemCur = ref({} as ExpressTempleteItem)
    const { showConfirm } = useDialog()

    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'batchButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '模板名称',
              field: 'name',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100
        },

        columns: [
          {
            title: '模板名称',
            field: 'name'
          },
          {
            title: '创建时间',
            field: 'createTime',
            minWidth: 150,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '创建人',
            field: 'createUser'
          },
          {
            title: '状态',
            fixed: 'right',
            slots: {
              default: 'status'
            },
            width: 100
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 180
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await marketingApi.getExpressTempleteList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    //启用禁用操作
    function handleForbidden(item) {
      showConfirm({
        content:
          item.status == 1 ? '确认禁用该运费模板？' : '确认启用运费模板？',
        onOk: async () => {
          try {
            await marketingApi.upDownExpressTemplete(item.id)
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    //新增
    function add() {
      optionItemCur.value = {
        noShippingProvinceTemp: []
      } as ExpressTempleteItem
      showDialog.value = true
    }

    //编辑
    function edit(item) {
      if (item.noShippingProvince) {
        item.noShippingProvinceTemp = item.noShippingProvince.split(',')
      } else {
        item.noShippingProvinceTemp = []
      }
      optionItemCur.value = cloneDeep(item)
      showDialog.value = true
    }

    //编辑/新增确定
    async function dialogConfirm() {
      if (!optionItemCur.value.name) {
        message.error('请输入模板名称')
        return
      }
      if (!optionItemCur.value.perTransitFee) {
        message.error('请输入初始邮费')
        return
      }
      if (!optionItemCur.value.incrItem || !optionItemCur.value.fee) {
        message.error('请输入邮费价格')
        return
      }

      try {
        const params = {
          ...optionItemCur.value,
          noShippingProvince:
            optionItemCur.value.noShippingProvinceTemp.join(',')
        }
        dialogLoading.value = true
        if (optionItemCur.value.id) {
          await marketingApi.editExpressTemplete(params)
        } else {
          await marketingApi.addExpressTemplete(params)
        }
        showDialog.value = false
        tableRef.value.refresh()
      } finally {
        dialogLoading.value = false
      }
    }

    return {
      tableRef,
      tableConfig,
      showDialog,
      dialogLoading,
      optionItemCur,
      pList,
      dialogConfirm,

      handleForbidden,
      add,
      edit
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            batchButtons: () => (
              <Space>
                <Button type="primary" onClick={() => this.add()}>
                  新增运费模板
                </Button>
              </Space>
            ),
            status: ({ row }) => {
              return (
                <Space>
                  {row.status == 0 ? (
                    <TypographyText type="danger">禁用</TypographyText>
                  ) : (
                    <TypographyText type="success">启用</TypographyText>
                  )}
                </Space>
              )
            },

            operation: ({ row }) => (
              <Space>
                <Button type="link" size="small" onClick={() => this.edit(row)}>
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleForbidden(row)}
                >
                  {row.status === 0 ? '启用' : '禁用'}
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showDialog}
          confirmLoading={this.dialogLoading}
          title={'编辑'}
          destroyOnClose
          onOk={this.dialogConfirm}
        >
          <Form labelCol={{ span: 4 }}>
            <FormItem label={'模板名称'} required>
              <Input
                maxlength={60}
                v-model:value={this.optionItemCur.name}
                placeholder="请输入"
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label={'初始邮费'} required>
              <InputNumber
                v-model:value={this.optionItemCur.perTransitFee}
                placeholder="请输入"
                min={0}
                maxlength={10}
                precision={2}
                style={{ width: '200px' }}
              />
              {` 元`}
            </FormItem>
            <FormItem label={'每增加'} required>
              <Space>
                <InputNumber
                  v-model:value={this.optionItemCur.incrItem}
                  placeholder="请输入"
                  min={0}
                  maxlength={10}
                  style={{ width: '80px' }}
                />
                {` 件  费用增加`}
                <InputNumber
                  v-model:value={this.optionItemCur.fee}
                  placeholder="请输入"
                  maxlength={10}
                  precision={2}
                  style={{ width: '80px' }}
                />
                {` 元`}
              </Space>
            </FormItem>
            <FormItem label={'不发货地区'}>
              <Select
                v-model:value={this.optionItemCur.noShippingProvinceTemp}
                mode="multiple"
                placeholder="请选择"
                style={{ width: '300px' }}
              >
                {this.pList.map(v => (
                  <SelectOption value={v}>{v}</SelectOption>
                ))}
              </Select>
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
